import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/bean/exterior_entity.dart';
import 'package:yuan_hang_app/bean/interior_entity.dart';
import 'package:yuan_hang_app/bean/user.dart';
import 'package:yuan_hang_app/bean/version_entity.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/home/model/leads.dart';
import 'package:yuan_hang_app/views/home/view/order/order_model.dart';
import 'package:yuan_hang_app/widget/common_attachment.dart';

import 'package:yuan_hang_app/widget/label_item.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

class OrderEditPage extends StatefulWidget {
  int? orderId;
  Leads? clueInfo;

  OrderEditPage({super.key, this.orderId, this.clueInfo});

  @override
  BaseState<OrderEditPage> createState() => _OrderEditPageState();
}

class _OrderEditPageState extends BaseState<OrderEditPage> {
  List<Map> modelList = WConstant.modelList;
  List<Map> versionList = [];
  List<Map> exteriorList = [];
  List<Map> innerList = [];
  List picList = [];
  List picUrlList = [];
  GlobalKey<LabelItemState>? modelKey;
  GlobalKey<LabelItemState>? exteriorKey;
  GlobalKey<LabelItemState>? versionKey;
  GlobalKey<LabelItemState>? interiorKey;
  GlobalKey<LabelItemState>? customerKey;
  GlobalKey<LabelItemState>? sexKey;
  GlobalKey<LabelItemState>? mobileKey;
  GlobalKey<LabelItemState>? custTypeKey;
  GlobalKey<LabelItemState>? firmNameKey;
  GlobalKey<LabelItemState>? idTypeKey;
  GlobalKey<LabelItemState>? idNoKey;
  GlobalKey<LabelItemState>? purchaseMethodKey;
  GlobalKey<LabelItemState>? deliveryCenterKey;

  GlobalKey<LabelItemState>? expectDateKey;
  GlobalKey<LabelItemState>? remarkKey;
  GlobalKey<CommonAttachmentState>? picKey;
  String exteriorId = "";
  String modelId = "";
  String saleMan = "";
  String shopName = "";
  Map editParams = {};

  ///编辑的时候传的参数，只传修改后的数据
  Map params = {
    "configModel": "", //车型
    "configSer": "", // 版本
    "configColor": "", //外色
    "configTrim": "", // 内饰
    "customerName": "", // 客户姓名
    "custType": 0, //客户类型
    "firmName": "", //公司名称
    "idType": "", //证件类型
    "idNo": "", //证件号
    "guideAmount": 0, // 官方指导价
    "salesAmount": 0, // 优惠价格
    "orderAmount": 0, // 市场零售价
    "depositAmount": 0, // 定金
    "finalAmount": 0, // 尾款
    "discountAmount": 0, //抵扣价
    "payType": 0, // 字典值  支付方式
    "purchaseMethod": 0,
    "dealerId": "", //直营店
    "saleMan": "", //销售顾问
    "deliveryCenter": 0, // 交付中心
    "expectDate": "", // 期望交付日期
    "estimatedDeliveryDate": "", //  预计交付日期
    "deliveryTime": "", //提车日期
    "remark": "", //备注
    "mobile": "", //手机号
  };
  User userInfo = WConstant().userInfo;
  late ScrollController _controller;
  List<Map> _attachmentImages = [];

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: widget.orderId == null ? "新增订单" : "编辑订单",
      resizeToBottomInset: true,
      child: Column(
        children: [
          Expanded(
            child: ListView(
              controller: _controller,
              padding: EdgeInsets.zero,
              children: [
                _cardItem("订单信息", _orderInfo()),
                _cardItem("客户信息", _customerInfo()),
                _cardItem("车辆明细", _carInfo()),
                _cardItem("其他信息", _otherInfo(), bottom: 10),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 10.px, horizontal: 15.px),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                GestureDetector(
                  onTap: () {
                    if (widget.orderId == null) {
                      //保存
                      CommonUtils.throttle(_saveOrder); //保存
                    } else {
                      //取消
                      CommonUtils.throttle(() {
                        save({"type": 1, "id": params["id"]});
                      });
                    }
                    CommonUtils.throttle(_saveOrder);
                  },
                  child: Container(
                    height: 48.px,
                    width: 120.px,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(24.px),
                        border: Border.all(color: WColors.border, width: 1.px),
                        color: WColors.white),
                    child: WText(
                      widget.orderId == null ? "保存" : "取消订单",
                      style: TextStyle(
                          color: WColors.primaryColor,
                          fontSize: WDimens.tsMedium),
                    ),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      if (widget.orderId == null) {
                        ///保存并支付定金
                        params["type"] = 3;
                        CommonUtils.throttle(_saveOrder);
                      } else {
                        ///保存
                        CommonUtils.throttle(_saveOrder);
                      }
                    },
                    child: Container(
                      margin: EdgeInsets.only(left: 10.px),
                      height: 48.px,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(24.px),
                          color: WColors.primaryColor),
                      child: WText(
                        widget.orderId == null ? "保存并支付定金" : "保存",
                        style: TextStyle(color: WColors.white, fontSize: 14.px),
                      ),
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initGlobalKey();
    showLoading();
    if (widget.orderId == null) {
      //新增
      if (widget.clueInfo != null) {
        //线索转订单
        print(json.encode(widget.clueInfo));
        params["clueId"] = widget.clueInfo!.id;
        params["configModel"] = widget.clueInfo!.modelId;
        params["sex"] = widget.clueInfo!.sex;
        params["mobile"] = widget.clueInfo!.phone;
        params["saleMan"] = widget.clueInfo!.saleman;
        params["customerName"] = widget.clueInfo!.customerName;
        params["custType"] = widget.clueInfo!.customerType;
        params["firmName"] = widget.clueInfo!.companyName;
        params["idType"] = widget.clueInfo!.idType;
        params["idNo"] = widget.clueInfo!.idNo;
        saleMan = widget.clueInfo!.salemanName!;
        shopName = widget.clueInfo!.shopName!;
      } else {
        saleMan = userInfo.employeeName!;
        shopName = userInfo.shopName!;
        params["saleMan"] = userInfo.userId;
        params["dealerId"] = userInfo.shopId;
      }
      getModelInfo();
    } else {
      getOrderDetail();
    }
  }

  void initGlobalKey() {
    _controller = ScrollController();
    _controller.addListener(() {
      if (_controller.position.pixels >= _controller.position.maxScrollExtent) {
        if (params["expectDate"] != null) {
          expectDateKey!.currentState?.refreshDate(params["expectDate"]);
        }
        picKey!.currentState?.refreshImageList(_attachmentImages);
      }
    });
    modelKey = GlobalKey(debugLabel: "modelKey");
    exteriorKey = GlobalKey(debugLabel: "exterior");
    versionKey = GlobalKey(debugLabel: "version");
    interiorKey = GlobalKey(debugLabel: "interior");
    customerKey = GlobalKey(debugLabel: "customerKey");
    sexKey = GlobalKey(debugLabel: "sexKey");
    mobileKey = GlobalKey(debugLabel: "modelKey");
    custTypeKey = GlobalKey(debugLabel: "custTypeKey");
    firmNameKey = GlobalKey(debugLabel: "firmNameKey");
    idTypeKey = GlobalKey(debugLabel: "idTypeKey");
    idNoKey = GlobalKey(debugLabel: "idNoKey");
    purchaseMethodKey = GlobalKey(debugLabel: "purchaseMethodKey");
    deliveryCenterKey = GlobalKey(debugLabel: "deliveryCenterKey");
    remarkKey = GlobalKey(debugLabel: "remarkKey");
    picKey = GlobalKey(debugLabel: "picKey");
    expectDateKey = GlobalKey(debugLabel: "expectDateKey");
  }

  void getModelInfo() {
    if (params["configModel"] == "") {
      params["configModel"] = modelList.isEmpty ? "" : modelList[0]["value"];
    }
    modelId = OrderModel.getId(modelList, params["configModel"]);
    getVersionByModeId();
    getExteriorModelById();
  }

  void getOrderDetail() {
    if (widget.orderId != null) {
      HttpUtils().get("${Api.getOrderDetail}/${widget.orderId}").then((data) {
        if (data.resultCode == 200) {
          params = data.data;
          editParams = {
            "id": params["id"],
          };
          getModelInfo();
          refreshWidget();
        } else if (data.resultCode == 500) {
          Toast.toast(data.errMsg ?? "");
        }
      });
    }
  }

  void refreshWidget() {
    modelKey!.currentState?.refreshList(modelList, params["configModel"]);
    customerKey!.currentState?.refreshInput(params["customerName"]);
    sexKey!.currentState?.refreshList(WConstant.sexList, params["sex"]);
    mobileKey!.currentState?.refreshInput(params["mobile"]);
    firmNameKey!.currentState?.refreshInput(params["firmName"] ?? "");
    custTypeKey!.currentState
        ?.refreshList(WConstant.customerTypeList, params["custType"]);
    idTypeKey!.currentState
        ?.refreshList(WConstant.cardTypeList, params["idType"]);
    idNoKey!.currentState?.refreshInput(params["idNo"]);
    deliveryCenterKey!.currentState?.refreshList(
        WConstant.directStoreStatusList, params["deliveryCenter"]);
    purchaseMethodKey!.currentState
        ?.refreshList(WConstant.buyCarWayList, params["purchaseMethod"]);
    remarkKey!.currentState?.refreshInput(params["remark"]);
    picList = (params["fileAddress"] ?? [])
        .map((item) => item["fileUploadId"])
        .toList();
    picUrlList =
        (params["fileAddress"] ?? []).map((item) => item["fileUrl"]).toList();
    picKey!.currentState?.refreshList(picUrlList);
    saleMan = params["createdPerson"] ?? "";
    shopName = params["shopName"] ?? "";
    print(params["fileAddress"]);
    print("------------------------------------");
    print(picList);
    setState(() {});
  }

  void getVersionByModeId() {
    CommonReqUtils.getVersionByModeId(modelId).then((value) {
      versionList = VersionEntity.exchangeLabelList(value);
      if (params["configSer"] == "") {
        params["configSer"] = versionList[0]["value"];
        if (widget.orderId != null) {
          editParams["configSer"] = params["configSer"];
        }
      }
      versionKey!.currentState?.refreshList(versionList, params["configSer"]);
    }).catchError((e) {
      hideLoading();
    });
  }

  void getExteriorModelById() {
    CommonReqUtils.getExteriorModelById(modelId).then((value) {
      exteriorList = ExteriorEntity.exchangeLabelList(value);
      if (params["configColor"] == "") {
        params["configColor"] = exteriorList[0]["value"];
        if (widget.orderId != null) {
          editParams["configColor"] = params["configColor"];
        }
        exteriorId = exteriorList[0]["id"].toString();
      } else {
        exteriorId = OrderModel.getId(exteriorList, params["configColor"]);
      }
      exteriorKey!.currentState
          ?.refreshList(exteriorList, params["configColor"]);
      getInteriorModelById();
    }).catchError((e) {
      hideLoading();
    });
  }

  void getInteriorModelById() {
    CommonReqUtils.getInteriorModelById(exteriorId).then((inner) {
      hideLoading();
      innerList = InteriorEntity.exchangeLabelList(inner);
      if (params["configTrim"] == "") {
        params["configTrim"] = innerList[0]["value"];
        if (widget.orderId != null) {
          editParams["configTrim"] = params["configTrim"];
        }
      }
      setState(() {});
      interiorKey!.currentState?.refreshList(innerList, params["configTrim"]);
    }).catchError((e) {
      hideLoading();
    });
  }

  void _saveOrder() {
    bool isCheck = OrderModel.check(params);
    if (isCheck) {
      save(widget.orderId != null ? editParams : params);
    }
  }

  void save(params) {
    showLoading();

    HttpUtils().post(Api.saveOrder, data: params).then((val) {
      hideLoading();
      if (val.resultCode == 200) {
        Toast.toast(val.data);
        RouteHelper.maybePop(context, true);
      } else {
        Toast.toast(val.errMsg);
      }
    }).catchError((onError) {
      hideLoading();
    });
  }

  Container _cardItem(String label, Widget child, {double bottom = 0}) {
    return Container(
      margin: EdgeInsets.only(
          top: 10.px, left: 15.px, right: 15.px, bottom: bottom.px),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(10.px)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 48.px,
            alignment: Alignment.centerLeft,
            child: Row(
              children: [
                WLine(
                  height: 16.px,
                  width: 4.px,
                  color: WColors.primaryColor,
                  marginRight: 15.px,
                ),
                WText(
                  label,
                  style: TextStyle(
                      fontSize: WDimens.tsLarge,
                      color: WColors.mainTextColor,
                      fontWeight: FontWeight.bold),
                )
              ],
            ),
          ),
          WLine(
            height: 0.5.px,
          ),
          child
        ],
      ),
    );
  }

  ///订单信息
  Column _orderInfo() {
    return Column(
      children: [
        LabelItem(
          label: "车型",
          isMust: true,
          key: modelKey,
          labelType: LabelType.DROW_DOWN,
          dataList: modelList,
          value: params["configModel"],
          onSelected: (value) {
            params["configModel"] = value;
            params["configSer"] = "";
            params["configColor"] = "";
            params["configTrim"] = "";
            if (widget.orderId != null) {
              editParams["configModel"] = value;
              editParams["configSer"] = "";
              editParams["configColor"] = "";
              editParams["configTrim"] = "";
            }
            modelId = OrderModel.getId(modelList, value);
            getVersionByModeId();
            getExteriorModelById();
          },
        ),
        LabelItem(
          key: versionKey,
          label: "版本",
          isModel: true,
          isMust: true,
          labelType: LabelType.DROW_DOWN,
          dataList: versionList,
          value: params["configSer"],
          onSelected: (value) {
            params["configSer"] = value;
            if (widget.orderId != null) {
              editParams["configSer"] = value;
            }
            setState(() {});
          },
        ),
        LabelItem(
          key: exteriorKey,
          label: "外观",
          isMust: true,
          labelType: LabelType.DROW_DOWN,
          dataList: exteriorList,
          value: params["configColor"],
          onSelected: (value) {
            params["configColor"] = value;
            params["configTrim"] = "";
            if (widget.orderId != null) {
              editParams["configColor"] = value;
              editParams["configTrim"] = "";
            }
            exteriorId = OrderModel.getId(exteriorList, value);
            getInteriorModelById();
          },
        ),
        LabelItem(
          key: interiorKey,
          label: "内饰",
          isMust: true,
          isLast: true,
          labelType: LabelType.DROW_DOWN,
          dataList: innerList,
          value: params["configTrim"],
          onSelected: (value) {
            params["configTrim"] = value;
            if (widget.orderId != null) {
              editParams["configTrim"] = value;
            }
            setState(() {});
          },
        ),
      ],
    );
  }

  ///客户信息
  Column _customerInfo() {
    return Column(
      children: [
        LabelItem(
          label: "客户名称",
          key: customerKey,
          isMust: true,
          labelType: LabelType.INPUT,
          maxLength: 50,
          value: StringUtils.safeGetValue(params["customerName"]),
          onChanged: (text) {
            params["customerName"] = text;
            if (widget.orderId != null) {
              editParams["customerName"] = text;
            }
            setState(() {});
          },
        ),
        LabelItem(
          label: "客户性别",
          isMust: true,
          key: sexKey,
          labelType: LabelType.LIST,
          value: params["sex"].toString(),
          dataList: WConstant.sexList,
          onSelected: (value) {
            params["sex"] = value;
            if (widget.orderId != null) {
              editParams["sex"] = value;
            }
            setState(() {});
          },
        ),
        LabelItem(
          label: "手机号码",
          key: mobileKey,
          isMust: true,
          maxLength: 11,
          labelType: LabelType.INPUT,
          textInputType: TextInputType.phone,
          value: StringUtils.safeGetValue(params["mobile"]),
          onChanged: (text) {
            params["mobile"] = text;
            if (widget.orderId != null) {
              editParams["mobile"] = text;
            }
            setState(() {});
          },
        ),
        LabelItem(
          label: "客户类型",
          key: custTypeKey,
          isMust: true,
          labelType: LabelType.LIST,
          value: params["custType"].toString(),
          dataList: WConstant.customerTypeList,
          onSelected: (value) {
            params["custType"] = value;
            if (widget.orderId != null) {
              editParams["custType"] = value;
            }
            setState(() {});
          },
        ),
        LabelItem(
          key: firmNameKey,
          label: "公司名称",
          labelType: LabelType.INPUT,
          value: StringUtils.safeGetValue(params["firmName"]),
          onChanged: (text) {
            params["firmName"] = text;
            if (widget.orderId != null) {
              editParams["firmName"] = text;
            }
            setState(() {});
          },
        ),
        LabelItem(
          key: idTypeKey,
          label: "证件类型",
          labelType: LabelType.DROW_DOWN,
          value: params["idType"].toString(),
          dataList: WConstant.cardTypeList,
          onSelected: (value) {
            params["idType"] = value;
            if (widget.orderId != null) {
              editParams["idType"] = value;
            }
            setState(() {});
          },
        ),
        LabelItem(
          key: idNoKey,
          isLast: true,
          label: "证件号码",
          labelType: LabelType.INPUT,
          value: StringUtils.safeGetValue(params["idNo"]),
          onChanged: (text) {
            params["idNo"] = text;
            if (widget.orderId != null) {
              editParams["idNo"] = text;
            }
            setState(() {});
          },
        ),
      ],
    );
  }

  ///车辆明细
  Column _carInfo() {
    return Column(
      children: [
        LabelItem(
          label: "官方指导价",
          value:
              StringUtils.safeGetValue(params["guideAmount"], placeHolder: "0"),
          isEnabled: false,
        ),
        LabelItem(
          label: "抵扣价",
          value: StringUtils.safeGetValue(params["discountAmount"],
              placeHolder: "0"),
          isEnabled: false,
        ),
        LabelItem(
          label: "市场零售价",
          value:
              StringUtils.safeGetValue(params["salesAmount"], placeHolder: "0"),
          isEnabled: false,
        ),
        LabelItem(
          label: "定金金额",
          value: StringUtils.safeGetValue(params["depositAmount"],
              placeHolder: "0"),
          isEnabled: false,
        ),
        LabelItem(
          label: "尾款",
          value:
              StringUtils.safeGetValue(params["finalAmount"], placeHolder: "0"),
          labelType: LabelType.TEXT,
          isEnabled: false,
        ),
        LabelItem(
          isLast: true,
          key: purchaseMethodKey,
          label: "购车方式",
          labelType: LabelType.LIST,
          value: params["purchaseMethod"].toString(),
          dataList: WConstant.buyCarWayList,
          onSelected: (value) {
            params["purchaseMethod"] = value;
            if (widget.orderId != null) {
              editParams["purchaseMethod"] = value;
            }
            setState(() {});
          },
        ),
      ],
    );
  }

  ///其他信息
  Column _otherInfo() {
    return Column(
      children: [
        LabelItem(
          label: "直营店",
          value: shopName,
          labelType: LabelType.TEXT,
        ),
        LabelItem(
          label: "销售顾问",
          value: saleMan,
          labelType: LabelType.TEXT,
        ),
        LabelItem(
          label: "交付中心",
          key: deliveryCenterKey,
          labelType: LabelType.LIST,
          value: params["deliveryCenter"].toString(),
          dataList: WConstant.directStoreStatusList,
          onSelected: (value) {
            params["deliveryCenter"] = value;
            if (widget.orderId != null) {
              editParams["deliveryCenter"] = value;
            }
            setState(() {});
          },
        ),
        LabelItem(
          label: "期望交付日期",
          key: expectDateKey,
          labelType: LabelType.DATE,
          minDateTime: DateTime.now(),
          selectedDate: StringUtils.safeGetValue(params["expectDate"]),
          onDateChanged: (date) {
            params["expectDate"] = date;
            if (widget.orderId != null) {
              editParams["expectDate"] = date;
            }
            setState(() {});
          },
        ),
        LabelItem(
          label: "预计交付日期",
          labelType: LabelType.DATE,

          selectedDate:
              StringUtils.safeGetValue(params["estimatedDeliveryDate"]),
          isEnabled: false,
        ),
        Offstage(
          offstage: widget.orderId == null,
          child: LabelItem(
            label: "提车日期",
            labelType: LabelType.DATE,
            selectedDate: StringUtils.safeGetValue(params["deliveryTime"]),
            isEnabled: false,
          ),
        ),
        CommonAttachment(
          picList: picList,
          picUrlList: picUrlList,
          key: picKey,
          onSelected: (values, images) {
            _attachmentImages = images;
            String files = StringUtils.getFileIds(values);
            params["fileList"] = files;
            print("========1=============$files");
            if (widget.orderId != null) {
              editParams["fileList"] = files;
            }
          },
        ),
        WLine(height: 1.px),
        LabelItem(
          isLast: true,
          labelType: LabelType.TEXTAREA,
          label: "订单备注",
          value: StringUtils.safeGetValue(params["remark"]),
          onChanged: (text) {
            params["remark"] = text;
            if (widget.orderId != null) {
              editParams["remark"] = text;
            }
          },
        ),
      ],
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
